package beans;

import java.io.IOException;

import java.util.Map;

import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;

import oracle.adf.share.logging.ADFLogger;
import oracle.adf.view.rich.component.rich.input.RichInputFile;

import oracle.binding.OperationBinding;

import oracle.jbo.domain.Number;

import org.apache.commons.io.IOUtils;
import org.apache.myfaces.trinidad.model.UploadedFile;

import utils.ADFUtils;


public class FileLoaderBean {

    private static final ADFLogger LOG = ADFLogger.createADFLogger("FileLoaderBean");
    private RichInputFile fileUploadComponent;

    public FileLoaderBean() {
    }

    private byte[] bytes;
    private UploadedFile file;

    public void uploadFile(ValueChangeEvent event) throws IOException {
        file = (UploadedFile)event.getNewValue();
        bytes = IOUtils.toByteArray(file.getInputStream());
        fileUploadComponent.resetValue();
    }

    public void addFishPicture(ActionEvent actionEvent) {

        OperationBinding add = ADFUtils.findOperation("addFishPhoto");
        Map params = add.getParamsMap();
        params.put("bytes", bytes);
        params.put("fileName", file.getFilename());
        Number rowId = (Number)add.execute();
        OperationBinding commit = ADFUtils.findOperation("Commit");
        commit.execute();

        OperationBinding updateSI = ADFUtils.findOperation("updateStillImage");
        Map map = updateSI.getParamsMap();
        map.put("rowId", rowId);
        updateSI.execute();
        commit.execute();
    }

    public void setFileUploadComponent(RichInputFile fileUploadComponent) {
        this.fileUploadComponent = fileUploadComponent;
    }

    public RichInputFile getFileUploadComponent() {
        return fileUploadComponent;
    }
}
